package com.yxc.controller;

import com.yxc.entity.Book;
import com.yxc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@Controller
public class BookController {

    @Autowired
    BookService bookService;


    //存储字符串类型的key-value
    @GetMapping("/save")
    @ResponseBody
    public String save(){
        bookService.setValue("123","123");
        return "新增成功";
    }
    //通过键获取字符串类型的值
    @GetMapping("/getValue")
    @ResponseBody
    public String getValue(){
        return bookService.getValue("123");
    }
    //删除某个键值对
    @GetMapping("/del/{key}")
    @ResponseBody
    public String del(@PathVariable String key){
        bookService.delete(key);
        return "删除成功";
    }
    //保存一本书
    @GetMapping("/saveBook")
    @ResponseBody
    public String saveBook(){
        bookService.saveBook(new Book(1,"C语言程序设计",50.0,"计算机",100,"101.jpg","","zhangsan",50));
        return "保存一本书成功";
    }
    //通过id号查找一本书
    @GetMapping("/getBookByKey")
    public String getBookByKey(Model model){
        Book book = bookService.getBookByKey(1);
        model.addAttribute("book",book);
        return "book";
    }

    @GetMapping("/delBook/{key}")
    @ResponseBody
    public String delBook(@PathVariable Integer key){
        bookService.delBook(key);
        return "删除图书成功";
    }
    //保存多本书 list
    @GetMapping("/saveBooks")
    @ResponseBody
    public String saveBooks(){
        List<Book> books = Arrays.asList(
                new Book(1,"C语言程序设计",50.0,"计算机",100,"101.jpg","1","zhangsan",50),
                new Book(2,"java语言程序设计",60.0,"计算机",100,"102.jpg","2","zhangsan",50),
                new Book(3,"python语言程序设计",70.0,"计算机",100,"103.jpg","3","zhangsan",50)
        );

        bookService.saveBooks("101",books);
        return "保存多本书成功";
    }
    //查找所有书
    @GetMapping("/findBooks")
    public String findBooks(Model model){
        List<Book> books = bookService.findBooks("101");
        model.addAttribute("books",books);
        return "books";
    }
    //从多本book集合中找到某个id的书
    @GetMapping("/findBookById/{id}")
    public String findBookById(@PathVariable Integer id,Model model){
        List<Book> books = bookService.findBooks("101");
        Book book = new Book();
        if (books!=null && !books.isEmpty()){
            book = books.get(id-1);
        }
        model.addAttribute("book",book);
        return "book";
    }
    //根据id删除book集合中的某本书
    @GetMapping("/deleteBook/{id}")
    public String deleteBook(@PathVariable Integer id,Model model){
        bookService.delBook(id);
        List<Book> books = bookService.findBooks("101");
        books.remove(id-1);
        bookService.saveBooks("101",books);
        model.addAttribute("books",books);
        return "books";
    }

}
